from Common.EventHandle import EventHandle
from Calendar.Calendar import *
from DataFeeder.QueryDividend import *
from FinancialAsset.AssetFactory import *

class DividendEvent(EventHandle):

	def __init__(self, start_date, end_date, exch_list):
	
		trd_dates = TradingCalendar(exch_list).date_series(start_date, end_date, Frequency.Daily)

		EventHandle.__init__(self, trd_dates)

	def create_activities(self, ref_date, portfolio = None):
		
		activity_list = []
		
		cash_dvd = query_cash_dividend(ref_date) 
		share_dvd = query_share_dividend(ref_date)
		
		holding = portfolio.holding(ref_date)
		
		if cash_dvd:
		
			for ticker, rate in cash_dvd.iteritems():
				
				stock = AssetFactory().acquire_asset('STOCK', ticker)
				
				if holding and holding.has_key(stock):
					cash = AssetFactory().acquire_asset('CASH', stock.currency())
					activity_list.append((ref_date, cash, holding[stock]*rate))
					
		if share_dvd:	
		
			for ticker, rate in share_dvd.iteritems():
			
				stock = AssetFactory().acquire_asset('STOCK', ticker)
				
				if holding and holding.has_key(stock):
					activity_list.append((ref_date, stock, holding[stock]*rate))	
					
		return activity_list
		
	@staticmethod	
	def event_name():
		return 'DIVIDEND'
				
					
			
